<template>
  <div class="createPost-container">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <h1 style="text-align:center">
              {{ postForm.title }}
            </h1>

            <div class="postInfo-container" style="border-top:1px solid #eee;text-align:center;padding-top:10px">
              作者：<b style="padding-right:20px">{{ postForm.isAnonymous?'匿名':(postForm.author?postForm.author:'该用户已删除') }}</b>
              发布时间：<b>{{ postForm.publishTime }}</b>
            </div>

          </el-col>
        </el-row>

        <el-form-item prop="content" style="clear:both;margin: 20px;font-size:16px;line-height:200%" v-html="postForm.content" />
        <el-form-item label="图片" style="clear:both">
          <a v-for="(item,index) in postForm.fileList" :key="index" :href="$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(item.id)" target="_blank">
            <img :src="$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(item.id)" class="avatar" style="float:left;margin:20px;">
          </a>
        </el-form-item>
        <h2 style="border-top:1px solid #bfcbd9;padding-top:20px;">提交高管</h2>
        <el-form-item style="margin-bottom: 30px;">
          <el-checkbox-group
            v-model="checkedUsers"
          >
            <span style="width:100px;float:left;text-align:right;font-size:14px;margin-right:10px;font-weight:bolder">高管：</span><el-checkbox v-for="(users,index) in PrimaryUsers.filter(item=>item.roleName==='高管')" :key="index" :label="users.id">{{ users.realName }}（{{ users.deptName }}）</el-checkbox><br>
            <span style="width:100px;float:left;text-align:right;font-size:14px;margin-right:10px;font-weight:bolder">部门领导：</span><el-checkbox v-for="(users,index) in PrimaryUsers.filter(item=>item.roleName==='部门领导')" :key="index+200" :label="users.id">{{ users.realName }}（{{ users.deptName }}）</el-checkbox><br>
          </el-checkbox-group>
          <el-button type="primary" :loading="submitloading" style="margin:0 0 20px 110px;" @click="submitForm">提交</el-button>
        </el-form-item>

        <h2 style="border-top:1px solid #bfcbd9;padding-top:20px;">管理员评论</h2>
        <el-input v-model="reply" type="textarea" style="width:800px;margin:0 0 20px 110px;" /><br>
        <el-button type="primary" :loading="submitloading2" style="margin:0 0 20px 110px;clear:both" @click="submitForm2">评论</el-button>

        <h2 style="border-top:1px solid #bfcbd9;padding-top:20px;">评论列表</h2>
        <el-table
          ref="replyTable"
          v-loading="replyListLoading"
          :data="replyList"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column align="center" prop="dataCreateDatetime" label="提交时间" width="150" />
          <el-table-column align="center" prop="replyUserName" label="姓名" width="100">
            <template slot-scope="scope">
              {{ postForm.isAnonymous&&scope.row.replyUserId===postForm.userId?'匿名':scope.row.replyUserName }}
            </template>
          </el-table-column>

          <el-table-column prop="state" align="center" label="状态" width="80">
            <template slot-scope="scope">
              <span>{{ stateText(scope.row.state) }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" prop="replyTime" label="评论时间" width="250" />
          <el-table-column prop="replyContent" label="评论内容" />

          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <el-popconfirm v-if="!scope.row.dataDeleted" title="确定删除该信息吗？" style="margin-left:10px;" @onConfirm="deleteData(scope.row.id)">
                <el-button slot="reference" type="danger" size="small" icon="el-icon-delete">删除</el-button>
              </el-popconfirm>
              <div v-else>已删除</div>
            </template>
          </el-table-column>

        </el-table>
      </div>
    </el-form>
  </div>
</template>

<script>

const defaultForm = {
  classCode: '',
  content: '', // 文章内容
  files: [], // 文章图片
  id: null,
  isTop: 0,
  publishTime: '', // 前台展示时间
  title: '' // 文章题目
}

export default {
  name: 'ArticleDetail',
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: '请将表单填写完整',
          type: 'error'
        })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      submitloading2: false,
      submitloading: false,
      reply: '',
      replyList: [],
      replyListLoading: false,
      checkedUsers: [],
      PrimaryUsers: [],
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      classOption: [],
      rules: {
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }]
      },
      tempRoute: {}
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('timestamp:' + val)
        this.getData(this.infoid)
        this.getPrimaryUsers(this.infoid)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    const day = new Date()
    day.setTime(day.getTime())
    this.postForm.publishTime = day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate())
  },
  created() {
    this.getDic()

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    deleteData(id) {
      this.$http
        .get('/api/busDirectExecutivesReply/removeReply?id=' + id)
        .then(response => {
          if (response.data.success === true) {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getData(this.infoid)
            this.getPrimaryUsers(this.infoid)
          } else {
            console.log('删除失败:' + response.data.message)
            this.$message({
              message: '删除失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    stateText(code) {
      switch (code) {
        case 0:
          return '未读'
        case 1:
          return '已读'
        case 2:
          return '已评论'
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      if (id) {
        this.infoLoading = true
        this.$http
          .get('/api/busDirectExecutives/getById?isAdmin=true&id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              this.postForm = response.data.result
              this.replyList = response.data.result.replyList
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      }
    },
    getDispatchList(id) {
      if (id) {
        this.replyListLoading = true
        this.$http
          .get('/api/busDirectExecutivesReply/getDispatchList?businessId=' + id)
          .then(response => {
            this.replyListLoading = false
            if (response.data.success === true) {
              // this.replyList = response.data.result
              this.checkedUsers = response.data.result.map(item => item.userId)
              this.reply = ''
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.replyListLoading = false
          })
      }
    },
    getDic() {
      const code = '01'
      this.$http
        .get('/api/sysDict/getByCode?enabled=true&code=' + code)
        .then(response => {
          this.stopDicLoading = false
          if (response.data.success === true) {
            this.classOption = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.stopDicLoading = false
        })
    },
    getPrimaryUsers(id) {
      this.$http
        .get('/api/sysUser/getPrimaryUsers')
        .then(response => {
          if (response.data.success === true) {
            this.PrimaryUsers = response.data.result
            console.log(this.PrimaryUsers.map(item => ({ id: item.id, value: item.realName })))
            this.getDispatchList(id)
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    submitForm() {
      if (this.checkedUsers && this.checkedUsers.length > 0) {
        const para = {
          businessId: this.infoid,
          users: this.PrimaryUsers.filter(item => this.checkedUsers.indexOf(item.id) > -1).map(item => ({ id: item.id, realName: item.realName }))
        }
        this.submitloading = true
        this.$http
          .post('/api/busDirectExecutivesReply/saveDispatch', para)
          .then(response => {
            this.submitloading = false
            if (response.data.success === true) {
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.getPrimaryUsers(this.infoid)
              this.$emit('dialogHide')
            } else {
              console.log('提交失败:' + response.data.message)
              this.$message({
                message: '提交失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
            this.submitloading = false
          })
      } else {
        this.$message({
          message: '至少选择一位用户提交',
          type: 'error'
        })
      }
    },
    submitForm2() {
      if (this.reply && this.reply !== '') {
        const para = {
          businessId: this.infoid,
          content: this.reply
        }
        this.submitloading2 = true
        this.$http
          .post('/api/busDirectExecutivesReply/saveReplyForAdmin', para)
          .then(response => {
            this.submitloading2 = false
            if (response.data.success === true) {
              this.$message({
                message: '评论成功',
                type: 'success'
              })
              this.getData(this.infoid)
              this.getPrimaryUsers(this.infoid)
              this.$emit('dialogHide')
            } else {
              console.log('评论失败:' + response.data.message)
              this.$message({
                message: '评论失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(function(error) {
            console.log(error)
            this.submitloading2 = false
          })
      } else {
        this.$message({
          message: '评论内容不能为空',
          type: 'error'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
